<?php
class Tourism_goods_category_spec_model extends CI_Model
{
    private $table  = 'tourism_goods_category_spec';
    private $table_2  = 'tourism_goods_category_attribute';
    
    public function insertCategorySpec($postData)
    {
        $data = array();
        $attribute_value = array_filter($postData['attribute_value']);
        foreach ($attribute_value as $key =>$val) {
            $data[$key]['attr_id'] = $postData['attr_id'];
            $data[$key]['attribute_value'] = $val;
        }
        return $this->db->insert_batch($this->table, $data);
    }
    
    /*
     * 数据处理
     * */
    private  function processing($data)
    {
        $param = str_replace('，',',',$data);
        $param = trim($param,',');
        return explode(',',$param);
    }

    /**
     * 根据attr_id 获取 tourism_goods_category_spec中的对应信息
     * @param int
     * @return object
     */
    public function getSpecByAttId($attr_id)
    {
        $this->db->where('attr_id',$attr_id);
        return $this->db->get($this->table);
    }

    /**
     * 根据attr_id 一组重现排列的字符串，用，分割
     * @param int
     * @return string
     */
    public function getSpecStringByAttId($attr_id)
    {
        $resultObj = $this->getSpecByAttId($attr_id);
        foreach($resultObj->result() as $item)
        {
            $lists[] = $item->attribute_value;
        }
        return implode(',',$lists);
    }
    
    public function deleteSpec($attr_id)
    {
        $this->db->where('attr_id', $attr_id);
        return $this->db->delete($this->table);
    }

    public function getSpec($attr_id)
    {
        $this->db->select('a.attr_name,s.attr_id,s.spec_id,s.attribute_value');
        $this->db->from($this->table_2.' as a');
        $this->db->where('s.attr_id',$attr_id);
        $this->db->join($this->table.' as s ','a.attr_id = s.attr_id');
        return $this->db->get();
    }

    public function updateSpec($spec_id,$param)
    {
        $this->db->where('spec_id', $spec_id);
        return $this->db->update($this->table, $param);
        $this->db->update();
    }
    
    public function addSpec($attr_id,$attribute_value)
    {
        if(!is_array($attribute_value)){
            $attribute_value = explode(',',$attribute_value);
        }

        foreach($attribute_value as $val){
            $param[]['attr_id'] = $attr_id;
            $param[]['attribute_value'] = $val;
            $this->db->insert_batch($this->table,$param);
        }
    }

    public function getSpecNameById($spec_id)
    {
        $this->db->where('spec_id',$spec_id);
        $result = $this->db->get($this->table)->row_array();
        return isset($result['attribute_value'])?$result['attribute_value']:'';
    }
}